package demo2.category.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import demo2.category.BookCategoryTree;

import java.io.IOException;
import java.io.InputStream;

public class LoadJsonTextFileServiceImpl implements LoadService {
    private final InputStream inStream;
    private final ObjectMapper objectMapper;

    public LoadJsonTextFileServiceImpl(InputStream inStream) {
        this.inStream = inStream;
        objectMapper = new ObjectMapper();
    }

    @Override
    public BookCategoryTree loadCategoryTree() {
        try {
            return objectMapper.readValue(inStream, BookCategoryTree.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error: loadCategoryTree() failed to parse text!", e);
        } catch (IOException e) {
            throw new RuntimeException("Error: loadCategoryTree() failed read input stream!", e);
        }
    }
}
